#  Copyright (c) 2021
#  User:SDUFE-Zhaocheng Lu
#  File:start_sign.py
#  Date:2021/08/16 23:45:16
import requests
import base64
import time, re
import lib


def post_ERROR(error_id):
    requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data={
        'user': 'DMSintalor',
        'pass': 'LzC200138',
        'softid': '914617',
        'id': error_id,
    })


class QD:
    qd_data = {
        'name': '',
        'sex': '',
        'study_id': '',
        'college_id': '',
        'address': '',
        'contact': '',
        'phone': '',
        'province_id': '',
        'city_id': '',
        'now_address': '',
        'now_status': '1',
        'now_status_msg': '',
        'partition_time': '',
        'behavior': '1',
        'travel_address': '',
        'back_address': '',
        'travel_start': '',
        'travel_back': '',
        'travel_type': '0',
        'travel_number': '',
        'is_public': '0',
        'country_travel': '0',
        'travel_msg': '',
        'other_msg': '',
        'verify': ''
    }

    def __init__(self, field_list: dict) -> None:
        super().__init__()
        self.login_cnt, self.login_status = 0, False
        self.qd_cnt, self.qd_status = 0, False
        self.sess = requests.session()
        self.sess.get('http://bcfl.sdufe.edu.cn/student/handle_ext.html')
        self.user = field_list['school_id']
        self.password = field_list['password']
        for field in lib.qd_field:
            self.qd_data[field] = field_list['usr_info'].get(field, '')

    def get_new_captcha(self):
        jpg = self.sess.get('http://bcfl.sdufe.edu.cn/index.php?g=api&m=checkcode&a=index&time=').content
        file = base64.b64encode(jpg)
        return file

    def get_captcha(self):
        file_base64 = self.get_new_captcha()
        url = 'http://upload.chaojiying.net/Upload/Processing.php'
        data = {
            'user': 'DMSintalor',
            'pass': 'LzC200138',
            'softid': '914617',
            'codetype': '4004',
            'len_min': 0,
            'file_base64': file_base64,
        }
        res = requests.post(url=url, data=data).json()
        return res['pic_str'], res['pic_id']

    def qd_start(self):
        while self.qd_cnt < lib.fail_times and not self.qd_status:
            verify_code, verify_id = self.get_captcha()
            self.qd_data['verify'] = verify_code
            qd_res = self.sess.post(url='http://bcfl.sdufe.edu.cn/Student/handle_ext_do', data=self.qd_data).json()
            if qd_res['code'] == 200:
                self.qd_status = True
            if qd_res['code'] == 201:
                post_ERROR(verify_id)
            self.qd_cnt += 1
        return self.qd_status

    def login_start(self):
        while self.login_cnt < lib.fail_times and not self.login_status:
            verify_code, verify_id = self.get_captcha()
            self.qd_data['verify'] = verify_code
            login_res = self.sess.post(url='http://bcfl.sdufe.edu.cn/Student/handle_login', data={
                'number': self.user,
                'card': self.password,
                'verify': verify_code
            }).json()
            if login_res['code'] == 200:
                self.login_status = True
            if login_res['code'] == 201:
                post_ERROR(verify_id)
            self.login_cnt += 1
        return self.login_status

    def check_sign(self):
        res = self.sess.get('http://bcfl.sdufe.edu.cn/Student/handle_person')
        contents = res.text
        pattern = 'stateDate.*?;'
        reg = re.compile(pattern)
        stateDate = re.findall(reg, contents)[0]
        return eval(eval(stateDate.replace('stateDate', '').replace(';', '').replace('=', ''))[-1]['state']) == 0
        # from lxml import etree
        #
        # res = self.sess.get('http://bcfl.sdufe.edu.cn/student/handle_ext.html')
        # doms = etree.HTML(res.text)
        #
        # qd_field = lib.data_field
        # fin = doms.xpath('//*[@id="{}"]/@value'.format('name'))[0]
        # fin = {}
        # for field in qd_field:
        #     if field == 'sex':
        #         fin[field] = doms.xpath('//*[@name="sex" and @checked]/@value')[0]
        #     elif field == 'college_id':
        #         fin[field] = doms.xpath('//*[@name="college_id"]//*[@selected]/@value')[0]
        #     elif field == 'province_id':
        #         fin[field] = doms.xpath('//*[@name="province_id"]//*[@selected]/@value')[0]
        #     elif field == 'city_id':
        #         fin[field] = ''
        #     else:
        #         fin[field] = doms.xpath('//*[@id="{}"]/@value'.format(field))[0]
        # return fin
